﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace CobraCms.Core.Utilities
{
    public class ReflectionUtils
    {
        public static List<Type> GetTypesFromExecutionDirectoryWithAttribute(Type attributeType, bool inherit=false)
        {
            var matchedTypes = new List<Type>();            
            var executionDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
            if (executionDirectory == null)
                return matchedTypes;

            var files = executionDirectory.GetFiles();
            
            foreach (var file in files)
            {
                try
                {
                    var assembly = Assembly.LoadFile(file.FullName);
                    foreach (var type in assembly.GetTypes())
                    {
                        if (type.GetCustomAttributes(attributeType, inherit).Length > 0)
                        {
                            matchedTypes.Add(type);
                        }
                    }
                }
                catch { }
            }

            return matchedTypes;
        }


        public static T GetAttributeInstanceFromType<T>(Type classType) where T: class, new()
        {
            var foundAttribute = classType.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == typeof(T)) as T;
            return foundAttribute;
        }
    }
}
